package com.lk.controller;

import com.lk.model.GiteeModel;
import com.lk.model.GiteeUserInfo;
import com.lk.third.gitee.GiteeConfig;
import com.lk.util.JsonUtil;
import com.lk.util.Result;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;

/**
 * 清楚token
 *
 * @author : com.com.lk
 * @date 2021/11/20 21:33
 **/
@RestController
@RequestMapping("/oauth")
public class TokenController {


    @Autowired
    @Qualifier("consumerTokenServices")
    private ConsumerTokenServices consumerTokenServices;

    @Autowired
    private GiteeConfig giteeConfig;

    /**
     * 清除token
     *
     * @param accessToken
     * @return
     */
    @GetMapping("/removeToken")
    public Boolean removeToken(String accessToken) {
        return consumerTokenServices.revokeToken(accessToken);
    }

    /**
     * gitee的回调地址
     *
     * @param code code
     * @return 返回gitee的用户信息
     */
    @GetMapping("/callback")
    public Result<GiteeUserInfo> callback(@RequestParam("code") String code) {
        // 获取到code
        // 然后根据code 去换取认证token
        GiteeModel giteeModel = sendPost("https://gitee.com/oauth/token", code);
        // 获取用户信息
        GiteeUserInfo giteeUserInfo = sendGet("https://gitee.com/api/v5/user", giteeModel.getAccess_token());
        return Result.success(giteeUserInfo);
    }

    public RequestConfig getRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true).build();
    }

    public GiteeModel sendPost(String url, String code) {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        GiteeModel giteeModel = null;
        try {

            post.setConfig(getRequestConfig());

            ArrayList<NameValuePair> parameters = new ArrayList<>();
            parameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
            parameters.add(new BasicNameValuePair("code", code));
            parameters.add(new BasicNameValuePair("client_id", giteeConfig.getClientId()));
            parameters.add(new BasicNameValuePair("redirect_uri", giteeConfig.getCallback()));
            parameters.add(new BasicNameValuePair("client_secret", giteeConfig.getClientsecret()));
            UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(parameters, "UTF-8");
            post.setEntity(entity1);
            CloseableHttpResponse response = client.execute(post);
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                String string = EntityUtils.toString(entity, "UTF-8");
                giteeModel = JsonUtil.stringToBean(string, GiteeModel.class);
            } else {
                System.out.println("请重试");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return giteeModel;
    }


    public GiteeUserInfo sendGet(String uri, String accessToken) {
        uri = uri + "?" + "access_token=" + accessToken;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(uri);
        GiteeUserInfo giteeUserInfo = null;
        try {
            get.setConfig(getRequestConfig());
            CloseableHttpResponse response = httpClient.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                String string = EntityUtils.toString(entity);
                giteeUserInfo = JsonUtil.stringToBean(string, GiteeUserInfo.class);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return giteeUserInfo;

    }

}
